package org.example.service.impl;

import com.github.pagehelper.PageHelper;
import org.example.dao.ModelDao;
import org.example.dao.RoleDao;
import org.example.domain.Model;
import org.example.domain.PageBean;
import org.example.domain.Role;
import org.example.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Jimmy
 * @version 1.0
 */
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;
    @Autowired
    private ModelDao modelDao;

    @Override
    public PageBean<Role> findByPage(int pagenum, int pagesize) {
        PageHelper.startPage(pagenum, pagesize);
        List<Role> roles = roleDao.findByPage();

        for (Role role : roles) {
            List<Model> models = new ArrayList<>();
            List<String> modelId = modelDao.findByRid(role.getRid());
            for (String i : modelId) {
                Model model = modelDao.findByMid(i);
                models.add(model);
            }
            role.setChildren(models);
        }

        int total = roleDao.findTotal();
        return new PageBean<>(total,pagenum,roles);
    }

    @Override
    public List<Role> findByPageNoPage() {
        List<Role> roles = roleDao.findByPage();
        for (Role role : roles) {
            List<Model> models = new ArrayList<>();
            List<String> modelId = modelDao.findByRid(role.getRid());
            for (String i : modelId) {
                Model model = modelDao.findByMid(i);
                models.add(model);
            }
            role.setChildren(models);
        }
        return roles;
    }

    @Override
    public Role findOneById(String rid) {
        return roleDao.findById(rid);
    }

    @Override
    public int addRole(Role role) {
        return roleDao.addRole(role);
    }

    @Override
    public int update(Role role) {
        return roleDao.update(role);
    }

    @Override
    public int delete(String rid) {
        return roleDao.delete(rid);
    }

    @Override
    public int addRolePower(String rid, List<String> modelIds) {
        int i = 0;
        for (String modelId : modelIds) {
            i = roleDao.addRolePower(rid,modelId);
        }
        return i;
    }

    @Override
    public int deleteRolePower(String rid, String modelId) {
        return roleDao.deleteRolePower(rid,modelId);
    }


}
